package com.example.service;

import com.example.pojo.SysRole;
import com.example.pojo.SysUser;
import com.example.repository.SysUserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 自定义的实现根据用户名查询用户信息的业务逻辑
 */
@Service
public class MyUserDetailsService implements UserDetailsService {


    @Resource
    private SysUserRepository sysUserRepository;

    /**
     * 根据用户名查询用户相关信息
     * @param username 登录的用户名
     * @return UserDetails 返回的数据是根据用户名查询出来的相关用户信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户相关信息
        SysUser sysUser = sysUserRepository.findByUsername(username);

        if (null == sysUser){
            throw new UsernameNotFoundException("用户不存在............");
        }
        //定义权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysRole> roles = sysUser.getRoles();
        if (Objects.nonNull(roles) && roles.size() != 0){
            for (SysRole role : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRole()));
            }
        }
        //将用户相关信息封装到User对象中
        User user = new User(username,sysUser.getPassword(),sysUser.getEnabled(),
                true,true,true,authorities);
        return user;
    }
}
